﻿using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace Map
{
    public enum TileType
    {
        Regular,
        Animated,
        Auto4,
        AutoDP
    }

    public class TileStruct
    {
        public TileType Type;

        public virtual short Value {get;set;}

        public short TileSetIndex;

        public static TileStruct[,] Array(int x, int y)
        {
            var arr = new TileStruct[x,y];
            for (var i = 0; i < x; i++)
            {
                for (var j = 0; j < y; j++)
                {
                    arr[i,j] = new TileStruct();
                }
            }
            return arr;
        }

        public virtual void UpdateValue(TileStructGrid grid, Point pos, bool Recurse = true)
        {
            if (!Recurse) return;

            var bounds = new Rectangle(0, 0, grid.Size.X, grid.Size.Y);
            for (int i = -1; i <= 1; i++)
            {
                for (int j = -1; j <= 1; j++)
                {
                    var newPos = new Point(pos.X + i, pos.Y + j);
                    if (newPos == pos || !bounds.Contains(newPos))
                        continue;


                    var tile = grid[newPos];
                    if (tile != null)
                        tile.UpdateValue(grid, newPos, false);
                }
            }
        }

        public virtual void DrawTile(SpriteBatch batch, MapStruct map, Rectangle destRect, Color color)
        {
            if (Value == -1) return;
            var tileSize = map.TileSize;
            var tileSet = map.TileSets[TileSetIndex];
            batch.Draw(tileSet.TilesImage,
                                         destRect,
                                         new Rectangle((Value % tileSet.TilesSize.X) * tileSize,
                                                          (Value / tileSet.TilesSize.X) * tileSize,
                                                          tileSize, tileSize),color);
        }
    }
}
